#include "soundprovider.h"

#include <QEventLoop>
#include <QDebug>

#define RESOURCE_LOCATION "/usr/share/lightsaber/"

Soundprovider::Soundprovider()
{
    qDebug() << "Initializing Soundprovider.";

    player   = new QMediaPlayer;
    playlist = new QMediaPlaylist;

    playlist->addMedia(QUrl::fromLocalFile(RESOURCE_LOCATION"on.wav"));
    playlist->addMedia(QUrl::fromLocalFile(RESOURCE_LOCATION"swing0.wav"));
    playlist->addMedia(QUrl::fromLocalFile(RESOURCE_LOCATION"swing1.wav"));
    playlist->addMedia(QUrl::fromLocalFile(RESOURCE_LOCATION"swing2.wav"));
    playlist->addMedia(QUrl::fromLocalFile(RESOURCE_LOCATION"swing3.wav"));
    playlist->addMedia(QUrl::fromLocalFile(RESOURCE_LOCATION"swing4.wav"));
    playlist->addMedia(QUrl::fromLocalFile(RESOURCE_LOCATION"swing5.wav"));
    playlist->addMedia(QUrl::fromLocalFile(RESOURCE_LOCATION"swing6.wav"));
    playlist->addMedia(QUrl::fromLocalFile(RESOURCE_LOCATION"swing7.wav"));

    playlist->setPlaybackMode(QMediaPlaylist::CurrentItemOnce);
    playlist->setCurrentIndex(0);

    player->setPlaylist(playlist);
    player->setVolume(100);

    play();
    {
        // call blocks until currentIndexChanged signal has been received.
        QEventLoop loop;
        loop.connect(playlist, SIGNAL(currentIndexChanged(int)), SLOT(quit()));
        loop.exec();
    }

    qDebug() << "playlist->mediaCount(): " << playlist->mediaCount();
    qDebug() << "Soundprovider has been initialized.";
}

Soundprovider::~Soundprovider()
{
    delete player;
    delete playlist;
}

void Soundprovider::play()
{
    player->play();
}

void Soundprovider::stop()
{
    player->stop();
}

void Soundprovider::playRandomSwing()
{
    // anything else is fine except 0.
    playlist->setCurrentIndex((rand()%(playlist->mediaCount()-1))+1);

    play();
}

void Soundprovider::setVolume(int volume)
{
    player->setVolume(volume);
}
